package com.zhang.infrastructure.model;

import com.zhang.infrastructure.model.constant.ExceptionConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.stream.Collectors;

/**
 * 异常处理类
 *
 * @author zhangfanjun
 * @date 2021/11/17
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = com.zhang.infrastructure.model.KingHoodException.class)
    @ResponseBody
    public KingHoodResponseVO kingHoodHandler(KingHoodException e) {

        log.error("KingHoodException异常:", e);
        return KingHoodResponseVO.fail(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public KingHoodResponseVO methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {

        String message = e.getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining(";"));
        return KingHoodResponseVO.fail(ExceptionConstant.CODE_NO_VALID, message);
    }

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public KingHoodResponseVO exceptionHandler(Exception e) {

        log.error("未知异常！原因是:", e);
        return KingHoodResponseVO.error(ExceptionConstant.CODE_BAD_SERVER, "发生异常", e.getMessage());
    }
}
